package com.ecdc.soexample;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AppOpsManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationManagerCompat;
import androidx.viewpager.widget.ViewPager;
import com.ecdc.annotation.BindViewUtils;
import com.ecdc.annotation.EcdcAnnotation;
import com.deep_tools.ecdc.R;import org.xutils.ex.DbException;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import adapter.ViewPagerAdapter;
import bluetooth.BluetoothCommandCode;
import bluetooth.BluetoothLeService;
import bluetooth.GattUpdateReceiver;
import bluetooth.MyServiceConnection;
import bluetooth.NotificationMonitor;
import bluetooth.PhoneService;
import ota.CheckSendDataUtils;
import ota.MyByte;
import ota.Myhex;
import transformer.CustomizeDetailEnty;
import transformer.GalleryTransformer;
import utils.DbUitls;
import utils.OtherUtil;
import utils.SharedpreferencesUtils;
import utils.ToastUtils;
import view.SwitchButton;

public class HomeActivity extends BaseActivity2 {

    private FrameLayout mRelativeLayout;
    public static HomeActivity mHomeActivity;

    private MyServiceConnection mMyServiceConnection;
    private GattUpdateReceiver mGattUpdateReceiver;
    private String  bluetoothDeviceAddress;

    //设置界面
    @EcdcAnnotation.EcdcAnno(R.id.tongbushijjan_view_watch_set)
    private TextView tongbushijjan_view_watch_set;
    @EcdcAnnotation.EcdcAnno(R.id.dayin_view_watch_set)
    private TextView dayin_view_watch_set;
    /*********************************** ota使用 ******************************************/
    //
    private int SELECT_FILE_REQUEST_CODE=1;
    //选择文件
    @EcdcAnnotation.EcdcAnno(R.id.selectFile_view_watch_set)
    private TextView selectFile_view_watch_set;
    //mtu
    @EcdcAnnotation.EcdcAnno(R.id.mtu_view_watch_set)
    private TextView mtu_view_watch_set;
    //进度条
    @EcdcAnnotation.EcdcAnno(R.id.progressbar_view_watch_set)
    private ProgressBar progressbar_view_watch_set;
    //蓝牙状态
    @EcdcAnnotation.EcdcAnno(R.id.bluetoothStatus_view_watch_set)
    private TextView bluetoothStatus_view_watch_set;





    /************************************************************************************/

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static boolean isNotificationEnabled(Context context) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
            return areNotificationsEnabled;
        }

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
        /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }



    @TargetApi(Build.VERSION_CODES.O)
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHomeActivity=this;

        setContentView(R.layout.activity_watch_home);
        bluetoothDeviceAddress=getIntent().getStringExtra("bluetoothDeviceAddress");

        //注册广播
        GattUpdateReceiver.mBluettothInterface=this;
        mGattUpdateReceiver=new GattUpdateReceiver();
        registerReceiver(new GattUpdateReceiver(), makeGattUpdateIntentFilter());// 开始广播

        // 绑定服务
        mMyServiceConnection= new MyServiceConnection(bluetoothDeviceAddress);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mMyServiceConnection, BIND_AUTO_CREATE);

        //类似于findviewbyid
        try {
            BindViewUtils.getInstance().initEcdcAnnotationActivity(this, this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        //监听事件
        onClickL();




    }



    @Override
    protected void onResume() {
        super.onResume();

    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    }

    @Override
    public void getCurrentMtu(String mtu) {
        super.getCurrentMtu(mtu);
//        Toast.makeText(HomeActivity.this, mtu, Toast.LENGTH_SHORT).show();
        mtu_view_watch_set.setText("当前mtu值:"+mtu);


    }

    /**
 * 监听
 */
  private void onClickL(){
      progressbar_view_watch_set.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
//              if(currentFlagOtaReupdate==-1){
//                  ToastUtils.getToastUtilsInstance().toastCenterStrip("上传完成，请重新选择资源文件",HomeActivity.this,Color.RED);
//                  return;
//              }
//
//              CheckSendDataUtils mCheckSendDataUtils = CheckSendDataUtils.getCheckSendDataUtilsInstance();
//              int mtuValusInt = Integer.parseInt(mtu_view_watch_set.getText().toString().split(":")[1]);
//              mCheckSendDataUtils.initCheckSendDataUtils(readFiledataByBytes, mtuValusInt);
//
//
//
//              byte[] mneedSendByte=null ;
//
//              for(int i=0;i<currentFlagOtaReupdate-1;i++){
//                  byte[] currentFlagStyleByte = CheckSendDataUtils.intToByteArray(chaFengBaoStyle);// 拆分包类型
//                  byte[] currentFlagNoByte = CheckSendDataUtils.intToByteArray(i);// 拆分包编号
//                  byte[] currentBedore = new byte[] { currentFlagStyleByte[3], currentFlagNoByte[2], currentFlagNoByte[3] };
//                  mneedSendByte = mCheckSendDataUtils.checkDataIsSatisfyMtuValus(currentBedore);
//              }
//
//              byte[] currentFlagStyleByte = CheckSendDataUtils.intToByteArray(chaFengBaoStyle);// 拆分包类型
//              byte[] currentFlagNoByte = CheckSendDataUtils.intToByteArray(currentFlagOtaReupdate);// 拆分包编号
//              byte[] currentBedore = new byte[] { currentFlagStyleByte[3], currentFlagNoByte[2], currentFlagNoByte[3] };
//              byte[]   mneedSendByte3 = mCheckSendDataUtils.checkDataIsSatisfyMtuValus(currentBedore);
//
//              BluetoothCommandCode.getCheckSendDataUtilsInstance().startUpdateOta(HomeActivity.this,mneedSendByte3);
//
////              fff();
//
//

          }
      });
      selectFile_view_watch_set.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {

              Method [] methods=new Method[1];
              try {
                  methods[0]= BluetoothCommandCode.class.getMethod("sendSetWatchTime");
                  BluetoothCommandCode.getCheckSendDataUtilsInstance(HomeActivity.this).excuteMethods(methods);

              } catch (NoSuchMethodException e) {
                  e.printStackTrace();
              }

          }
      });
      tongbushijjan_view_watch_set.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {

              /****************************同步手表数据*************************************/

        Method [] methods=new Method[1];
        try {
            methods[0]= BluetoothCommandCode.class.getMethod("sendFindWatch");
//            methods[1]= BluetoothCommandCode.class.getMethod("sendElectricQuantit");
            BluetoothCommandCode.getCheckSendDataUtilsInstance(HomeActivity.this).excuteMethods(methods);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
          }
      });
  }

    @Override
    public void bluetoothResponse(String data) {
        super.bluetoothResponse(data);
        ToastUtils.getToastUtilsInstance().toastCenterStrip("蓝牙回复数据："+data,this,Color.GREEN);
//        Toast.makeText(App.context,"蓝牙回复数据："+data,Toast.LENGTH_SHORT).show();

    }

    //获取手表电量
    @Override
    public void getCurrentElectricQuantit(String electricQuantit) {

    }
    //获取手表电量
    @Override
    public void getCurrentElectricQuantit2(String electricQuantit) {


    }
    //更新蓝牙状态
    @Override
    public void updateBluetoothStatus(String electricQuantit) {
      if(electricQuantit.contains("蓝牙连接")){
          bluetoothStatus_view_watch_set.setText("蓝牙状态:已连接");
          SharedpreferencesUtils.getCheckSendDataUtilsInstance().saveBluetoothAddress(bluetoothDeviceAddress,this);
      }else if(electricQuantit.contains("蓝牙断开")){
          GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_NOTIFY=null;
          bluetoothStatus_view_watch_set.setText("蓝牙状态:断开");

      }else if(electricQuantit.contains("蓝牙关闭")){
          bluetoothStatus_view_watch_set.setText("蓝牙状态:断开");
          GattUpdateReceiver.bluetoothGattCharacteristicUUID_NOTIFY_NOTIFY=null;

      }else if(electricQuantit.contains("蓝牙打开")){
          String bluetoothAddress=SharedpreferencesUtils.getCheckSendDataUtilsInstance().getBluetoothAddress(this);
          mMyServiceConnection.connectBluetooth(bluetoothAddress);
          Toast.makeText(App.context,bluetoothAddress,Toast.LENGTH_SHORT).show();
      }

    }

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); // 蓝牙状态广播
        intentFilter.addAction(BluetoothLeService.EXTRA_DATA_MTU); // 蓝牙状态广播
        intentFilter.addAction(BluetoothLeService.ACTION_NOTIFICATION); // 通知消息广播
        intentFilter.addAction(BluetoothLeService.ACTION_CALL); // 通知消息广播


        return intentFilter;
    }
   //ota升级
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void otaUpdate(boolean isUpdate,String data) {
        super.otaUpdate(isUpdate,data);

    }

}
